<template>
    <div class="component">
        <!--面包屑导航-->
        <Breadcrumb :menulist="[`${componentType == 1 ? '项目' : '产品'}`, '表单']" :componentType="componentType"></Breadcrumb>

        <!--table-->
        <el-card class="box-card" shadow="hover">
            <div slot="header" class="tabHeader">
                <!--<p class="tit">表单列表</p>-->
                <el-button type="text" @click="getTreesList">打开组件节点</el-button>
                <span>{{componentSelect}}</span>
                <el-button type="primary" icon="el-icon-plus" @click="openAddForm" style="margin-left: auto">添加表单</el-button>
            </div>

            <el-table stripe :data="list.list" current-row-key="formId" @row-click="clickRow" style="width: 100%">
                <!--<el-table-column label="表单ID" prop="formId"></el-table-column>-->
                <el-table-column label="表单编码" prop="formCode"></el-table-column>
                <el-table-column label="表单名称" prop="formName"></el-table-column>
                <el-table-column label="表单模版" prop="formType.displayName"></el-table-column>
                <el-table-column label="关联主模型" prop="modelName"></el-table-column>
                <el-table-column label="所属组件" prop="componentName"></el-table-column>
                <el-table-column label="访问地址" prop="url"></el-table-column>
                <el-table-column label="表单宽度" prop="formWidth"></el-table-column>
                <el-table-column label="表单高度" prop="formHeight"></el-table-column>
                <el-table-column label="是否权限控制" prop="isAuthControll" :formatter="formatter"></el-table-column>
                <el-table-column label="创建时间" prop="createTime"></el-table-column>
                <el-table-column label="创建用户" prop="createUserName"></el-table-column>
                <el-table-column label="修改时间" prop="modifyTime"></el-table-column>
                <el-table-column label="修改用户" prop="modifyUserName"></el-table-column>
                <el-table-column label="描述" prop="description"></el-table-column>
                <el-table-column label="操作" width="150" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" @click.stop="openEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button slot="reference" size="mini" type="danger" @click.stop="openDelForm(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    background
                    layout="slot, total, prev, pager, next, jumper"
                    :total="list.total"
                    :current-page.sync="currentPage"
                    :page-size="rows"
                    @current-change="changePage"
            >
                <el-button v-if="list.list.length>0" icon="el-icon-refresh" type="primary" style="margin-right: 10px; background: #409EFF; color:#fff" @click="getFormList"></el-button>
            </el-pagination>
        </el-card>

        <!--抽屉-组件树-->
        <el-drawer
                title="组件库"
                :visible.sync="show_tree"
                direction="ltr"
                :with-header="false"
                size="30%">
            <div class="drawerTitle">选择组件库</div>
            <el-tree
                    :data="treeData"
                    node-key="id"
                    class="tree"
                    :default-expand-all="true"
                    :props="treeDefaultProps"
                    @node-click="clickNode">
            </el-tree>
        </el-drawer>

        <!--添加表单-->
        <el-drawer
                title="添加Form"
                :show-close="false"
                :with-header="false"
                :before-close="cancelForm"
                :visible.sync="showAddForm"
                direction="rtl"
                ref="drawer"
                :destroy-on-close="true"
        >
            <div class="drawerTitle">{{type === 1 ? '新增表单' : type === 2 ? '编辑表单' : '删除表单'}}</div>
            <div class="add-drawer">
                <el-form :model="form" :rules="rules" ref="ruleForm">
                    <el-form-item :label-width="formLabelWidth" label="删除提示" v-if="type===3">
                        <el-input v-model="msg" type="textarea" autocomplete="off" disabled></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="表单编码" prop="formCode">
                        <el-input v-model="form.formCode" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="表单名称" prop="formName">
                        <el-input v-model="form.formName" autocomplete="off" :disabled="type === 3"></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="关联主模型" prop="modelId">
                        <el-select v-model="form.modelId" style="width: 100%;" placeholder="请选择" :disabled="type === 2 || type === 3">
                            <el-option v-for="item in modelsList" :key="item.modelId" :label="item.modelName" :value="item.modelId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="表单模版" prop="formType">
                        <el-select v-model="form.formType" style="width: 100%;" placeholder="请选择" :disabled="type === 2 || type === 3">
                            <el-option label="List" value="0"></el-option>
                            <el-option label="AddDialog" value="1"></el-option>
                            <el-option label="EditDialog" value="2"></el-option>
                            <el-option label="Maintain" value="3"></el-option>
                            <el-option label="Lookup" value="4"></el-option>
                            <el-option label="Other" value="5"></el-option>
                            <el-option label="ViewDialog" value="6"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="表单宽度" prop="formWidth">
                        <el-input v-model="form.formWidth" autocomplete="off" :disabled="type === 3"></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="表单高度" prop="formHeight">
                        <el-input v-model="form.formHeight" autocomplete="off" :disabled="type === 3"></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="描述" prop="description">
                        <el-input v-model="form.description" :disabled="type === 3"></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="访问地址">
                        <el-input v-model="form.url" disabled></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="所属组件">
                        <el-input v-model="form.componentName" disabled></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="所属模块">
                        <el-input v-model="form.moduleName" disabled></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="所属项目" v-if="componentType==1">
                        <el-input v-model="form.solutionName" disabled></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="所属产品">
                        <el-input v-model="form.topSolutionName" disabled></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="参照值项">
                        <el-input v-model="form.valueField" disabled></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="参照编码项">
                        <el-input v-model="form.codeField" disabled></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="参照名称项">
                        <el-input v-model="form.nameField" disabled></el-input>
                    </el-form-item>
                    <el-form-item :label-width="formLabelWidth" label="是否权限控制">
                        <el-switch v-model="form.isAuthControll" :disabled="type === 3"></el-switch>
                    </el-form-item>
                </el-form>

                <div class="add-drawer_foot">
                    <el-button @click="cancelForm()">取 消</el-button>
                    <el-button plain icon="el-icon-delete" @click="reset()" v-if="type === 1">清除</el-button>
                    <el-button type="primary" @click="ok('ruleForm')" :loading="addLoading">{{ addLoading ? '提交中 ...' : '确 定' }}</el-button>
                </div>
            </div>
        </el-drawer>
    </div>
</template>


<script>
    import Breadcrumb from "@/components/Breadcrumb.vue";
    import {request, url} from "@/api/request";

    export default {
        name: "ComponentForm",
        components: {
            Breadcrumb
        },
        data() {
            return {
                treeData:[],
                treeDefaultProps: {
                    children: 'childs',
                    label: 'label'
                },
                show_tree:false,
                componentID:'',
                componentSelect: '-',
                list:{
                    list:[],
                },
                currentPage:1,
                rows:10,

                addLoading:false,
                showAddForm:false,
                formLabelWidth: '100px',
                type:1,//1新增 2编辑 3删除
                form:{
                    isAuthControll:true,
                },
                rules:{
                    formCode: [
                        { required: true, message: '必填', trigger: 'change' },
                    ],
                    formName: [
                        { required: true, message: '必填', trigger: 'change' },
                    ],
                    modelId: [
                        { required: true, message: '必选', trigger: 'change' },
                    ],
                    formType: [
                        { required: true, message: '必选', trigger: 'change' },
                    ],
                },
                modelsList:[],
                FormDefault:{},
                msg:'',
            };
        },
        props: {
            componentType: {
                type: Number,
                default: 1,//1组件，2产品
            },
        },
        created() {
            // console.log('created');
            // if (this.componentID) {
            //     // this.getFormList();
            //     console.log(1);
            // }
        },
        mounted() {
            let LocationParams = this.getLocationParams();
            if (LocationParams.componentID) {
                this.componentID = LocationParams.componentID;
                this.componentSelect = decodeURIComponent(LocationParams.componentSelect);
                this.getFormList(1);
            }
        },
        methods: {
            getTreesList() {
                console.log(this.$store.state.solution_global);
                if (this.$store.state.solution_global) {
                    this.show_tree = true;
                    let solutionId = this.$store.state.solution_global.solutionId;
                    request(`${url.navigationtree}/${solutionId}`,{},res=>{
                        // let newData = [];
                        // newData.push(res.data.root)
                        // this.treeData = newData;
                        // this.show_tree = true;
                        let newData = res.data.root.childs;
                        this.treeData = this.filterTree(newData);
                    })
                }
                else{
                    this.$message({
                        message:'请先选择解决方案。',
                        type:'warning',
                    })
                }
            },
            // 过滤 tree 数据重新整合
            filterTree(data) {
                if(!data) {
                    return false;
                }
                return data.map(item => {
                    if (item.childs) {
                        this.filterTree(item.childs);
                    }
                    item.label = `${item.label}（${item.navigationType.displayName}）`
                    return item;
                }).filter(item => item);
            },
            clickNode(data, parent){
                if (data.navigationType.displayName === 'Component') {
                    this.componentSelect = '';
                    // this.componentSelect = `${data.label ? ' ' : ''}${data.label}`;
                    this.componentID = data.id;
                    this.getFormList();
                    this.getTreeNode(parent);
                    this.show_tree = false;
                } else {
                    this.$message({
                        message: '请先选择组件(Component)',
                        type: 'warning'
                    });
                }
            },
            //获取当前树节点和其父级节点
            getTreeNode(node){
                if (node.parent) {
                    this.componentSelect = `${node.label} ${this.componentSelect ? '>':''} ${this.componentSelect}`;
                    this.getTreeNode(node.parent); //递归
                }
            },
            changePage(e){
                this.currentPage = e;
                this.getFormList();
            },
            getFormList(upData){
                request(`${url.getFormList}/${this.componentID}`,{
                    data:{
                        currentPage:this.currentPage,
                        rows:this.rows,
                        solutionId:this.$store.state.solution_global.solutionId,
                    }
                },res=>{
                    // console.log(res);
                    this.list = res.data;
                    // location.href = `${location.href}?componentID=${this.componentID}&componentSelect=${this.componentSelect}`
                    !upData && this.$router.push({path: `Form?componentID=${this.componentID}&componentSelect=${encodeURIComponent(this.componentSelect)}`})
                })
            },
            cancelForm() {
                this.addLoading = false;
                this.showAddForm = false;
                this.reset();
            },
            //打开添加表单
            openAddForm(){
                if (!this.componentID) {
                    this.$message({
                        message:'请先选择组件节点。',
                        type:'warning',
                    })
                    return;
                }
                this.type = 1;
                this.showAddForm = true;
                this.reset();
                this.$refs.ruleForm.resetFields();
                //请求关联主模型和所属组件等
                this.getSelectModelsList();
                this.getFormDefault();
            },
            openEdit(index, row){
                this.type = 2;
                this.showAddForm = true;
                this.form = {
                    ...row,
                    isAuthControll:!!row.isAuthControll,
                    formType:row.formType.code+'',

                }
                this.getSelectModelsList();
                this.getFormDefault();
                // this.$refs.ruleForm.resetFields();
            },
            openDelForm(index, row){
                this.type = 3;
                this.showAddForm = true;
                this.form = {
                    ...row,
                    isAuthControll:!!row.isAuthControll,
                    formType:row.formType.code+'',

                }
                request(`${url.formsDeleteCheck}/${row.formId}`,{
                    // method:'delete',
                },res=>{
                    this.msg = res.message;
                })
                this.getSelectModelsList();
                this.getFormDefault();
            },
            getSelectModelsList(){
                request(`${url.getSelectModelsList}/${this.componentID}`,{
                    data:{
                        solutionId:this.$store.state.solution_global.solutionId,
                    }
                },res=>{
                    this.modelsList = res.data;
                })
            },
            getFormDefault(){
                request(`${url.getFormDefault}/${this.componentID}`,{},res=>{
                    this.form = {
                        ...this.form,
                        ...res.data,
                    };
                })
            },
            ok(formName){
                //
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.addLoading = true;
                        if (this.type === 1) {
                            this.addForm();
                        }
                        else if(this.type === 2){
                            this.editForm();
                        }
                        else if(this.type === 3){
                            this.delForm();
                        }
                    }
                    else {
                        this.$message({
                            message:'有未完成的必填项！',
                            type:'warning',
                        })
                        return false;
                    }
                });
            },
            addForm(){
                this.form.isAuthControll  ? this.form.isAuthControll = 1 : this.form.isAuthControll = 0;
                request(`${url.addForms}`,{
                    method:'POST',
                    // loading:1,
                    data:{
                        ...this.form,
                        solutionId:this.$store.state.solution_global.solutionId,
                    },
                },res=>{
                    this.addLoading = false;
                    this.$refs.drawer.closeDrawer();
                    this.reset('ruleForm');
                    this.$notify.success(res.message);
                    this.getFormList();
                },()=>{
                    this.addLoading = false;
                })
            },
            editForm(){
                request(`${url.addForms}/${this.form.formId}`,{
                    method:'PUT',
                    data:{
                        formName:this.form.formName,
                        formWidth:this.form.formWidth,
                        formHeight:this.form.formHeight,
                        description:this.form.description,
                        isAuthControll:this.form.isAuthControll ? 1 : 0,
                        solutionId:this.$store.state.solution_global.solutionId,
                    },
                },res=>{
                    this.addLoading = false;
                    this.$refs.drawer.closeDrawer();
                    this.reset('ruleForm');
                    this.$notify.success(res.message);
                    this.getFormList();
                },()=>{
                    this.addLoading = false;
                })
            },
            delForm(){
                request(`${url.addForms}/${this.form.formId}`,{
                    method:'delete',
                },res=>{
                    this.addLoading = false;
                    this.$refs.drawer.closeDrawer();
                    this.reset('ruleForm');
                    this.$notify.success(res.message);
                    this.getFormList();
                },()=>{
                    this.addLoading = false;
                })
            },
            reset(){
                this.type === 1 ?
                this.form = {
                    ...this.form,
                    formCode:'',
                    formName:'',
                    modelId:'',
                    formType:'',
                    formWidth:'',
                    formHeight:'',
                    description:'',
                    url:'',
                    isAuthControll:!!this.form.isAuthControll,
                } :
                    this.form = {
                        ...this.form,
                        formName:'',
                        formWidth:'',
                        formHeight:'',
                        description:'',
                        url:'',
                        isAuthControll:!!this.form.isAuthControll,
                    }
            },
            formatter(row, column, cellValue, index){
                return cellValue ? '是' : '否';
            },
            clickRow(row){
                this.$router.push({path: `Part?formId=${row.formId}&componentID=${this.componentID}`})
            }
        }
    };
</script>

<style scoped>
    .add-drawer{
        padding:20px 20px 20px 15px;
    }
    .add-drawer_foot{
        text-align: center;
    }
    .drawerTitle {
        line-height: 70px;
        font-size: 20px;
        margin-left: 30px;
    }

    .tree {
        margin-left: 30px;

    }
    .tabHeader{
        display: flex;
        align-items: center;
    }
    .tit{
        font-weight: bold;
        font-size: 20px;
        display: inline;
        margin-right: 15px;
    }
    .box-card{
        margin-bottom: 15px;
    }

</style>
